//
//  JSSEmotionKeyboard.swift
//  WeiBoItem
//
//  Created by jss on 16/4/27.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit
import SnapKit

class JSSEmotionKeyboard: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func  setupUI() {
        
        
//        backgroundColor = UIColor.grayColor()
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //把底部的emoticonToolbar添加到自定义的这个键盘上
        addSubview(emoticonToolbar)
        
        //添加中间的collectionView
        addSubview(emoticonCollectionview)
        
        //添加pageContol
        addSubview(pageControl)
        
        //约束emoticonToolbar
        emoticonToolbar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(self)
            make.height.equalTo(37)
        }
        
        //emoticonCollectionview的约束
        emoticonCollectionview.snp_makeConstraints { (make) -> Void in
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(emoticonToolbar.snp_top)
        }
        
        //pageControl的约束
        pageControl.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(emoticonToolbar)
            make.bottom.equalTo(emoticonToolbar.snp_top)
        }
        
        
        //注册cell
        
        //表情按钮的闭包
        emoticonToolbar.emoticonBtnClickClosure = {[weak self] (type)->() in
            
            print(type)
            
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            self?.emoticonCollectionview.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            
            //设置pageControl的数据显示
              self?.showPageControl(indexPath)
            
        }
        
        
        
        //需要在界面完全展示出来再去移动(collectionView的大小已经确定,已经走过一遍数据源方法,主线程空闲的时候再去执行下面的要实现的方法)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emoticonCollectionview.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            
            //选中底部的按钮
            self.emoticonToolbar.selectedSection = indexPath.section
            
            //设置pageContol 显示内容
            self.showPageControl(indexPath)
            
        }
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let flowLayout = emoticonCollectionview.collectionViewLayout as? UICollectionViewFlowLayout
        
        flowLayout?.itemSize = CGSize(width: SCREENW, height: self.frame.height - self.emoticonToolbar.frame.height)
        
    }
    
    
    //懒加载分页控件(pageControl)
    private lazy var pageControl:UIPageControl = {
        
        let control = UIPageControl()
        
        control.hidden = true
      
        control.currentPageIndicatorTintColor = UIColor.orangeColor()
        
        control.pageIndicatorTintColor = UIColor.blackColor()
        
//        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
//        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        // 关闭用户交互
        control.userInteractionEnabled = false
        
        
        
        return control
    }()
    
    
    //懒加载表情按钮自定义键盘下的toolbar
    private lazy var emoticonToolbar:JSSEmoticonToolBarView = JSSEmoticonToolBarView(frame: CGRectZero)
    
    
    
    //懒加载中间的collectionView
    private lazy var emoticonCollectionview:UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: SCREENW, height: self.frame.height - self.emoticonToolbar.frame.height)
        
        flowLayout.minimumInteritemSpacing = 0
        
        flowLayout.minimumLineSpacing = 0
        
        flowLayout.scrollDirection = .Horizontal
        
        
        let collView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        //设置数据源代理
        collView.dataSource = self
        //设置代理
        collView.delegate = self
        
        collView.registerClass(JSSEmoticonpPageCell.self, forCellWithReuseIdentifier: "cell")
        
//        collView.backgroundColor = UIColor.orangeColor()
        collView.backgroundColor = UIColor.clearColor()
        
        collView.pagingEnabled = true
        
        collView.bounces = false
        
        collView.showsHorizontalScrollIndicator = false
        
        return collView
        
    }()
    
}

//实现emoticonCollectionview的数据源方法 分类
extension JSSEmotionKeyboard: UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    //返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.allEmoticons.count
    }
    
    //返回每组多少行
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.allEmoticons[section].count
    }
    
    //返回每一页对应的cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! JSSEmoticonpPageCell
        
        cell.indexPath = indexPath
        
//        cell.backgroundColor = randomColor
        
        //传进去的每一个cell里面的按钮还是一个数组(相当于cell里数据还是数组)
        cell.emoticons = JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.allEmoticons[indexPath.section][indexPath.item]
        
        return cell
    }
    
    
    //实现代理方法
    // 监听 collectionView的滚动，判断当前滚动到第几组，再去选中对应组的按钮
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //目的:取到collectionView当前显示的出来多的那个cell的indexPath所对应的组
        
        //1.先取到collectionView的中心点
        var center = scrollView.center
        
        //2.然后再取到 collectionView的中心点 + 滚动的距离(cell的偏移量)
        center.x = scrollView.contentOffset.x + center.x
        
        //3取到collectionView当前显示的cell
        let cells = emoticonCollectionview.visibleCells()
        
        //4定义个indexPath
        let indexPath :NSIndexPath
        
        //5.进行判断
        //当屏幕上显示两个cell的时候
        
        if cells.count == 2 {
            //先取到当前对应显示的第一个和最后一个cell
            let firstcell = cells.first
            let lastcell = cells.last
            //取到显示多的那个cell的indexPath
            if CGRectContainsPoint((firstcell?.frame)!, center){
                //判断第一个cell的范围是否包含算出来的中心点,如实包含说明第一个cell显示的多
                indexPath = emoticonCollectionview.indexPathForCell(firstcell!)!
            }else{
                
                //否则就是最后一个cell显示的多 找到显示多的cell后把相对应indexPath赋给indexPath
                indexPath = emoticonCollectionview.indexPathForCell(lastcell!)!
            }
        }else{
            //当屏幕上显示一个cell的时候
            indexPath = emoticonCollectionview.indexPathForCell(cells.first!)!
            
        }
        
        
        print(indexPath.section)  //取到cell的indexPath
        //取到cell的indexPath后 赋给emoticonToolbar(控制下面按钮)
        
        
        emoticonToolbar.selectedSection = indexPath.section
        
        
        //设置pageControl显示的内容

        showPageControl(indexPath)
        
        
        
    }
    
    
    //设置pagecontrol显示的内容
    private func showPageControl(indexPath:NSIndexPath){
        
        //更改pageControl的总页数
        pageControl.numberOfPages = JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.allEmoticons[indexPath.section].count
        
        pageControl.currentPage = indexPath.item
        
        //如果是最近表情不要显示pagecontrol
        
        pageControl.hidden = indexPath.section == 0
        
    }
    
    
}
